﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace MetroTube.BusinessLogic
{
    public class YouTubeHtmlWebPage
    {
        private string _url;
        private string _sourceCode;

        public YouTubeHtmlWebPage(string url)
        {
            if (url == null)
                throw new ArgumentNullException();

            /*
            if (!Regex.IsMatch(url, @"^http:\/\/(?:www\.)?youtube.com\/watch\?(?=.*v=\w+)(?:\S+)?$"))
                throw new ArgumentException();
             */

            if (!Regex.IsMatch(url, @"http://(?:www\.)?youtu(?:be\.com/watch\?v=|\.be/)(\w*)(&(amp;)?[\w\?=]*)?"))
                throw new ArgumentException();


            _url = url;
        }

        public string Url
        {
            get { return _url; }
        }

        public string SourceCode
        {
            get
            {
                if (_sourceCode != null)
                    return _sourceCode;

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                StreamReader streamReader = new StreamReader(response.GetResponseStream());

                _sourceCode = streamReader.ReadToEnd();

                streamReader.Close();

                return _sourceCode;
            }
        }
    }
}
